package cn.edu.hstc.wm.ui;

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import cn.edu.hstc.wm.AppApplication;
import cn.edu.hstc.wm.Constants;
import cn.edu.hstc.wm.R;
import cn.edu.hstc.wm.service.UpdateManager;
import cn.edu.hstc.wm.utils.FileUtils;
import cn.edu.hstc.wm.utils.IntentUtil;
import cn.edu.hstc.wm.utils.MethodsCompat;
import cn.edu.hstc.wm.widget.CustomToast;

/**
 * @ClassName: SettingActivity
 * @Description:App 系统设置
 * 
 * @ModificationHistory
 */
public class SettingActivity extends PreferenceActivity implements OnPreferenceClickListener {
	public static final String TAG = "SettingActivity";

	/**
	 * 设置的key / value 对应的
	 */
	private static final String KEY_USER = "account";
	private static final String KEY_MYINFO = "myinfo";
	private static final String KEY_AUTO_UPDATE = "auto_update";
	private static final String KEY_ITEM_COUNT = "item_count";
	private static final String KEY_LOAD_IMAGE = "load_image";
	private static final String KEY_START_CHECK_UPDATE = "start_check_update";
	private static final String KEY_AUTO_START = "auto_start";
	private static final String KEY_CLEAR_CACHE = "clear_cache";
	private static final String KEY_WELCOME_PAGE = "welcome_page";
	private static final String KEY_MANUAL = "manual";
	private static final String KEY_UPDATE_LOG = "update_log";
	private static final String KEY_FEED_BACK = "feedback";
	private static final String KEY_UPDATE = "update";
	private static final String KEY_ABOUT = "about";

	AppApplication mAppication;

	SharedPreferences mPreferences;

	private Preference accountPreference;
	private Preference myInfoPreference;
	private CheckBoxPreference autoUpdatePreference;
	private ListPreference itemCountPreference;
	private CheckBoxPreference loadImagePreference;
	private CheckBoxPreference startCheckUpdatePreference;
	private CheckBoxPreference autoStartPreference;
	private Preference cachePreference;
	private Preference welcomePreference;
	private Preference manualPreference;
	private Preference updateLogPreference;
	private Preference feedbackPreference;
	private Preference updatePreference;
	private Preference aboutPreference;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mAppication = (AppApplication) getApplication();
		// 获得SharedPreferences
		mPreferences = PreferenceManager.getDefaultSharedPreferences(this);

		initPreferencesView();
		initActionbar();

		findPreference();
		setPreferences();
	}

	@Override
	public void onActivityResult(int requestCode,int resultCode,Intent intent){
		if (resultCode==Constants.LOGIN_TYPE_GO_ORDER && requestCode==0) {
			finish();
		}
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	private void initActionbar() {
		ImageButton backButton = (ImageButton) findViewById(R.id.ib_actionbar_back);
		TextView titleView = (TextView) findViewById(R.id.tv_actionbar_title);

		backButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();

			}
		});
		titleView.setText("设置管理");
	}

	@SuppressWarnings("deprecation")
	private void initPreferencesView() {
		// 设置视图,从xml文件载入
		addPreferencesFromResource(R.xml.setting);
		ListView localListView = getListView();
		localListView.setBackgroundColor(0);
		localListView.setCacheColorHint(0);

		// 添加自定义的Actionbar View
		((ViewGroup) localListView.getParent()).removeView(localListView);
		ViewGroup localViewGroup = (ViewGroup) getLayoutInflater().inflate(R.layout.setting_layout, null);
		((ViewGroup) localViewGroup.findViewById(R.id.fl_setting_content)).addView(localListView, -1, -1);
		setContentView(localViewGroup);
	}

	@SuppressWarnings("deprecation")
	private void findPreference() {
		accountPreference = findPreference(KEY_USER);
		myInfoPreference = findPreference(KEY_MYINFO);
		autoUpdatePreference = (CheckBoxPreference) findPreference(KEY_AUTO_UPDATE);
		itemCountPreference = (ListPreference) findPreference(KEY_ITEM_COUNT);
		loadImagePreference = (CheckBoxPreference) findPreference(KEY_LOAD_IMAGE);
		startCheckUpdatePreference = (CheckBoxPreference) findPreference(KEY_START_CHECK_UPDATE);
		autoStartPreference = (CheckBoxPreference) findPreference(KEY_AUTO_START);
		cachePreference = findPreference(KEY_CLEAR_CACHE);
		welcomePreference = findPreference(KEY_WELCOME_PAGE);
		manualPreference = findPreference(KEY_MANUAL);
		updateLogPreference = findPreference(KEY_UPDATE_LOG);
		feedbackPreference = findPreference(KEY_FEED_BACK);
		updatePreference = findPreference(KEY_UPDATE);
		aboutPreference = findPreference(KEY_ABOUT);
	}

	private void setPreferences() {

		appIsLogin();
		accountPreference.setOnPreferenceClickListener(this);

		myInfoPreference.setOnPreferenceClickListener(this);

		autoUpdatePreference.setOnPreferenceClickListener(this);

		itemCountPreference.setOnPreferenceClickListener(this);

		startCheckUpdatePreference.setOnPreferenceClickListener(this);

		loadImagePreference.setOnPreferenceClickListener(this);

		autoStartPreference.setOnPreferenceClickListener(this);

		// 显示缓存大小
		cachePreference.setSummary(getCacheSize());
		cachePreference.setOnPreferenceClickListener(this);

		welcomePreference.setOnPreferenceClickListener(this);

		manualPreference.setOnPreferenceClickListener(this);

		updateLogPreference.setOnPreferenceClickListener(this);

		feedbackPreference.setOnPreferenceClickListener(this);

		updatePreference.setOnPreferenceClickListener(this);

		aboutPreference.setOnPreferenceClickListener(this);

	}

	private void appIsLogin() {
		if (mAppication.isLogin()) {
			accountPreference.setTitle(R.string.app_user_logout); // 显示注销登录
		} else {
			accountPreference.setTitle(R.string.app_user_login); // 显示登录
		}
	}

	private void user2LoginOrLogout() {
		accountPreference.setTitle(R.string.app_user_login);
		UIHelper.showLoginOrLogoutDialog(this, Constants.LOGIN_TYPE_SETTING_LOGIN);
	}

	private void goUserInfo() {
		UIHelper.showUserInfo(this, Constants.LOGIN_TYPE_SETTING_INFO);
	}

	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {

		return true;
	}

	/**
	 * 退出
	 */
	public void back(View view) {
		finish();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		Log.d(TAG, "onNewIntent");
		super.onNewIntent(intent);
		// 接收到返回结果为true
		if (intent.getBooleanExtra(Constants.LOGIN_RESULT, false)) {
			// 说明用户登录成功
			accountPreference.setTitle(R.string.app_user_logout);
		}
	}

	public boolean onPreferenceClick(Preference preference) {
		String prefKey = preference.getKey();
		// 点击用户
		if (prefKey.equals(KEY_USER)) {
			// 用户登录，注销
			user2LoginOrLogout();

		} else if (equal(prefKey, KEY_MYINFO)) {
			// 用户信息
			goUserInfo();

		} else if (equal(prefKey, KEY_AUTO_UPDATE)) {
			// 自动刷新数据
			if (autoUpdatePreference.isChecked()) {
				CustomToast.make(mAppication).setText("自动更新数据").show();
			}

		} else if (equal(prefKey, KEY_ITEM_COUNT)) {
			// 每次加载条目数
			CustomToast.make(mAppication).setText("每次加载 " + itemCountPreference.getValue() + " 条").show();

		} else if (equal(prefKey, KEY_LOAD_IMAGE)) {
			// 加载图片

		} else if (equal(prefKey, KEY_START_CHECK_UPDATE)) {
			// 程序启动时检测更新
			if (startCheckUpdatePreference.isChecked()) {
				CustomToast.make(mAppication).setText("程序启动时检查更新").show();
			}

		} else if (equal(prefKey, KEY_AUTO_START)) {
			// 开机自启动
			if (autoStartPreference.isChecked()) {
				CustomToast.make(mAppication).setText("开机启动").show();
			}

		} else if (equal(prefKey, KEY_CLEAR_CACHE)) {
			// 清除缓存
			if (getCacheSize().equals("0KB")) {
				CustomToast.make(mAppication).setText("无需清除了").show();
			}
			clearCache();

		} else if (equal(prefKey, KEY_WELCOME_PAGE)) {
			// 欢迎界面
			Intent intent = new Intent(this, AppGuide.class);
			intent.putExtra(Constants.START_GUIDE_PAGE_TYPE, Constants.START_GUIDE_PAGE_TYPE_SETTING);
			startActivity(intent);

		} else if (equal(prefKey, KEY_MANUAL)) {
			// 引导指南
			CustomToast.make(mAppication).setText("引导指南").show();

		} else if (equal(prefKey, KEY_UPDATE_LOG)) {
			// 更新日志
			UIHelper.showChangeLog(this);

		} else if (equal(prefKey, KEY_FEED_BACK)) {
			// 反馈意见
			Intent intent = new Intent(this, UserFeedback.class);
			startActivity(intent);

		} else if (equal(prefKey, KEY_UPDATE)) {
			// 检测更新
			UpdateManager.getUpdateManager(SettingActivity.this).checkUpdate(true);

		} else if (equal(prefKey, KEY_ABOUT)) {
			// 关于
			IntentUtil.startActivity(this, AboutApp.class);
		}
		return true;
	}

	private boolean equal(String str1, String str2) {
		return str1.equals(str2);
	}

	private String getCacheSize() {
		// 计算缓存大小
		long fileSize = 0;
		String cacheSize = "0KB";
		File filesDir = getFilesDir();
		File cacheDir = getCacheDir();

		fileSize += FileUtils.getDirSize(filesDir);
		fileSize += FileUtils.getDirSize(cacheDir);
		// 2.2版本才有将应用缓存转移到sd卡的功能
		if (mAppication.isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)) {
			File externalCacheDir = MethodsCompat.getExternalCacheDir(this);
			fileSize += FileUtils.getDirSize(externalCacheDir);
		}
		if (fileSize > 0)
			cacheSize = FileUtils.formatFileSize(fileSize);
		return cacheSize;
	}

	private void clearCache() {
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 1) {
					cachePreference.setSummary("0KB");
					CustomToast.make(mAppication).setText("缓存清除成功").show();
				} else {
					cachePreference.setSummary(getCacheSize());
					CustomToast.make(mAppication).setText("缓存清除失败").show();
				}
			}
		};
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					FileUtils.clearCacheFolder(mAppication.getCacheDir(), System.currentTimeMillis());
					msg.what = 1;
				} catch (Exception e) {
					e.printStackTrace();
					msg.what = -1;
				}
				handler.sendMessage(msg);
			}
		}.start();
	}
}
